/**
 * Alibaba.com.cn Inc.
 * Copyright (c) 2004-2021 All Rights Reserved.
 */
package com.smart.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.xuyanwu.spring.file.storage.FileInfo;
import cn.xuyanwu.spring.file.storage.FileStorageService;
import com.smart.common.WebResponse;
import com.smart.common.utils.AssertUtil;
import com.smart.model.vo.ProjectVO;
import com.smart.service.ProjectService;
import com.smart.utils.OSSUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;

/**
 * @author zhanghong
 * @version FileController.java, v 0.1 2023/6/26 21:12 下午 FileController Exp $$
 */
@Slf4j
@RestController
@RequestMapping("/file")
@Api(tags = {"A通用模块#文件模块"})
public class FileController {

    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private ProjectService projectService;

    @ApiOperation(value = "上传", httpMethod = "POST")
    @ApiResponses(value = {@ApiResponse(code = 200, message = "success")})
    @PostMapping("/upload")
    public WebResponse<String> upload(MultipartFile file) {
        FileInfo fileInfo = fileStorageService.of(file).upload();
        return WebResponse.build(fileInfo.getUrl());
    }

    @ApiOperation(value = "上传", httpMethod = "POST")
    @ApiResponses(value = {@ApiResponse(code = 200, message = "success")})
    @PostMapping("/uploadHotWork/{projectId}")
    public WebResponse<String> upload3(MultipartFile multipartFile, @PathVariable("projectId") Long projectId) throws IOException {
        ProjectVO project = projectService.getByKey(projectId);
        AssertUtil.assertNotNull(project, "项目不存在");
        String dateStr = DateUtil.format(new Date(), "yyyyMMdd");
        String fileName = multipartFile.getOriginalFilename();
        String fileExt = fileName.substring(fileName.lastIndexOf(".")+1);
        fileName = IdUtil.randomUUID() + "." + fileExt;
        String objectName = StrUtil.format("hotWork/{}/{}/{}", project.getId(), dateStr, fileName);
        return WebResponse.build(OSSUtil.uploadMultipartFile(multipartFile, objectName));
        //return WebResponse.build(OSSUtil.uploadMultipartFile2(multipartFile, objectName));
    }

}
